package my.learnDB.relation.dao;


import my.learnDB.relation.domain.Account;
import my.learnDB.relation.domain.AccountCa;
import my.learnDB.relation.domain.User;
import my.learnDB.relation.domain.UserCascade;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class ObjectQuery {

    @Autowired
    UserCascadeDao userCascadeDao;  // 放弃外键维护, 支持级联

    @Autowired
    AccountDao accountDao;

    @Test
    @Transactional  // noSession
    public void 对象导航查询(){
        Optional<UserCascade> optional = userCascadeDao.findById(1);
        assert optional.isPresent();

        UserCascade userCascade = optional.get();

        // 对象导航查询
        List<AccountCa> accounts = userCascade.getAccounts();
        // 使用对象
        accounts.forEach(System.out::println);
    }

    @Test
    @Transactional  // noSession
    // 不推荐立即加载
    public void objectQuery延迟加载(){
        Optional<UserCascade> optional = userCascadeDao.findById(1);
        assert optional.isPresent();

        UserCascade userCascade = optional.get();

        // 对象导航查询
        List<AccountCa> accounts = userCascade.getAccounts();

        // accounts.forEach(System.out::println);
    }


    @Test
    @Transactional
    public void 对象导航多对一(){

        Optional<Account> optional = accountDao.findById(1);
        assert optional.isPresent();
        Account account = optional.get();
        User user = account.getUser();  // 默认懒加载
         System.out.println(user);
    }

    // 立即加载
    // select * from user  outer join account on user0_.id=accounts1_.userId
    // where user0_.id=?

}
